import {BizKfExtraProColumnType} from '@/components';
import * as API from '@/services';
import {Divider, message, Space, Typography} from 'antd';
import {KfModal, KfPagingTablePage, KfPagingTablePagePropsAction, useBackendEnum} from 'kf-web-library';
import React, {useRef} from 'react';
import {useLocation, useAccess} from 'umi';
import QuickRoleForm from './components/QuickForm';
import "./index.less"
import * as service from "@/services/system/user/UserService";
import {getIdentityTypeDesc} from "@/utils/auth";

type Entity = API.User;
type EntityPageQueryParams = API.UserPageQueryParams;
const entityTypeName = '用户';
const EntityQuickForm = QuickRoleForm;

interface EntityTableListProps {
}

/**
 * 用户 列表页面
 */
const EntityTableList: React.FC<EntityTableListProps> = (props) => {
  const location = useLocation();
  const access = useAccess();
  const {enumDict, enumTypeDict, getBackendEnum} = useBackendEnum();
  const actionRef = useRef<KfPagingTablePagePropsAction<Entity, EntityPageQueryParams>>();

  return (
    <KfPagingTablePage<Entity, EntityPageQueryParams, BizKfExtraProColumnType>
      actionRef={actionRef}
      entityTypeName={entityTypeName}
      pagingQuery={(p) => {
        return service.queryUsers({
          ...p,
          type: ["CONSUMER"]
        })
      }}
      opActionsDef={{
        single: {
          deleteOne: (record) => {
            KfModal.deleteConfirm(record.id, () => {
              API.deleteUser(record.id!).then((res) => {
                if (res.flag) {
                  message.info('删除成功');
                  actionRef.current?.reload();
                }
              });
            });
          },
          enableOne: (record) => {
            KfModal.confirm('启用', record.nickname, () => {
              service.enableUser(record.id!).then((res) => {
                if (res.flag) {
                  message.info('启用成功');
                  actionRef.current?.reload();
                }
              });
            });
          },
          disableOne: (record) => {
            KfModal.confirm('停用', record.nickname, () => {
              service.disableUser(record.id!).then((res) => {
                if (res.flag) {
                  message.info('停用成功');
                  actionRef.current?.reload();
                }
              });
            });
          },
        },
        multi: {
          deleteMultiple: (records) => {
            KfModal.batchActionConfirm('删除', records.length, () => {
              API.deleteUsers(records.map((r) => r.id!)).then((res) => {
                if (res.flag) {
                  message.info('批量删除成功');
                  actionRef.current?.reload();
                }
              });
            });
          },
        },
      }}
      opFloatingsDef={{
        noargs: {
          createModal: {
            show: true,
            buttonText: '新增',
            fltRender: () => ({
              title: `新建`,
              content: <EntityQuickForm formType={'create'}/>,
            }),
          },
        },
        single: {
          modifyModal: (record) => ({
            title: `编辑`,
            content: <EntityQuickForm formType={'modify'} bizId={record.id}/>,
          }),
          viewModal: (record) => ({
            fltType: 'modal',
            title: `查看`,
            content: <EntityQuickForm formType={'view'} bizId={record.id}/>,
          }),
        },
      }}
      proTable={{
        tableBarActions: (action, rows) => {
          return [];
        },
        search: {
          optionRender: (searchConfig, formProps, dom) => [
            ...dom,
          ],
        },
      }}
      columns={[
        {
          title: '关键字',
          dataIndex: 'searchText',
          sorter: false,
          hideInTable: true,
          hideInForm: true,
          fieldProps: {
            placeholder: '模糊检索昵称和登录账号',
          },
        },
        {
          title: '序号',
          width: 50,
          key: '_seq_index_',
          align: 'center',
          hideInSearch: true,
          valueType: 'index',
          render: (dom, record, index) => {
            const pageInfo = actionRef.current?.queryParams();
            return ((pageInfo?.current || 1) - 1) * (pageInfo?.pageSize || 0) + (index + 1);
          },
        },
        {
          title: '登录账号',
          width: 180,
          dataIndex: nameof<Entity>((x) => x.auths),
          sorter: false,
          hideInSearch: true,
          ellipsis: false,
          renderText: (_, record) => {
            return (
              <Space direction={"vertical"} size={3}>
                {record.auths?.map((auth) => {
                  return <div><span>{getIdentityTypeDesc(auth.identityType)}</span>{auth.identifier}</div>
                })}
              </Space>
            );
          },
        },
        {
          title: '用户昵称',
          width: 140,
          dataIndex: nameof<Entity>((x) => x.nickname),
          sorter: false,
          hideInSearch: true,
          ellipsis: true,
        },
        {
          title: '联系电话',
          width: 135,
          ellipsis: true,
          dataIndex: nameof<Entity>((x) => x.phone),
          hideInSearch: true,
        },
        {
          title: '启用',
          width: 110,
          dataIndex: nameof<Entity>((x) => x.enabled),
          sorter: false,
          filters: undefined,
          formItemProps: {},
          valueEnum: {
            true: {text: '已启用', status: 'Success'},
            false: {text: '未启用', status: 'Error'},
          },
        },
        {
          title: '注册时间',
          dataIndex: 'createTimeRange',
          sorter: false,
          hideInTable: true,
          hideInForm: true,
          valueType: 'dateTimeRange',
        },
        {
          title: '注册时间',
          width: 180,
          ellipsis: true,
          dataIndex: nameof<Entity>((x) => x.createTime),
          hideInSearch: true,
        },
        {
          title: '操作',
          fixed: 'right',
          width: 240,
          dataIndex: 'option',
          valueType: 'option',
          render: (_, record) => (
            <Space size={0} split={<Divider type="vertical"/>}>
              <a onClick={() => actionRef.current?.openFloating.single?.viewModal(record)}>查看</a>
              {
                access.hasAnyAuthority("ROLE_ADMIN", "ROLE_NODE_ADMIN") && (
                  <>
                    {record.id !== '1' && (
                      <>
                        {!record.enabled ? (
                          <a onClick={() => actionRef.current?.executeAction.single?.enableOne(record)}>启用</a>
                        ) : (
                          <a onClick={() => actionRef.current?.executeAction.single?.disableOne(record)}>停用</a>
                        )}
                      </>
                    )}
                    <a onClick={() => actionRef.current?.openFloating.single?.modifyModal(record)}>编辑</a>
                    <a onClick={() => actionRef.current?.openFloating.single?.authListModal(record)}>关联账号</a>
                    {
                      <>
                        {record.id !== '1' && (
                          <>
                            <a onClick={() => actionRef.current?.executeAction.single?.deleteOne(record)}>
                              <Typography.Text type="danger">删除</Typography.Text>
                            </a>
                          </>
                        )}
                      </>
                    }
                  </>
                )
              }
            </Space>
          ),
        },
      ]}
    />
  );
};

export default EntityTableList;
